package com.db.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.db.common.annotation.RequiredLog;
import com.db.common.exception.ServiceException;
import com.db.common.vo.Node;
import com.db.dao.SysDeptDao;
import com.db.dao.SysUserDao;
import com.db.pojo.SysDept;
import com.db.service.SysDeptService;

@Service
public class SysDeptServiceImpl implements SysDeptService{

	@Autowired
	private SysDeptDao sysDeptDao;
	@Autowired
	private SysUserDao sysUserDao;
	
	@Override
	public List<Map<String, Object>> findObjects() {
		return sysDeptDao.findObjects();
	}

	@Override
	public List<Node> findZtreeDeptNodes() {
		return sysDeptDao.findZtreeDeptNodes();
	}

	@Override
	@RequiredLog("添加部门")
	public int saveObject(SysDept entity) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new ServiceException("部门名不能为空");
		int rows;
		try {
			rows=sysDeptDao.insertObject(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("保存失败");
		}
		return rows;
	}

	@Override
	@RequiredLog("删除部门")
	public int deleteObject(Integer id) {
		if(id==null||id<=0)
			throw new ServiceException("数据不合法，id="+id);
		int childCount=sysDeptDao.getChildCount(id);
		if(childCount>0)
			throw new ServiceException("此元素有子元素，不允许删除");
		int userCount=sysUserDao.getUserCountByDeptId(id);
		if(userCount>0)
			throw new ServiceException("此部门有员工，不允许删除");
		int rows=sysDeptDao.deleteObject(id);
		if(rows==0)
			throw new ServiceException("此信息可能已经不存在");
		return rows;
	}

	@Override
	@RequiredLog("更新部门")
	public int updateObject(SysDept entity) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new ServiceException("保存对象不能为空");
		int rows=sysDeptDao.updateObject(entity);
		if(rows==0)
		throw new ServiceException("记录可能已经不存在");
		return rows;
	}

}
